package com.zjb.datastructure.sort;

import org.springframework.util.ResourceUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class MergeSort {
    static void merge(int [] result,int[] a,int [] b) {

        int index = 0, aIndex = 0, bIndex = 0;
        while (aIndex < a.length && bIndex < b.length) {
            //如果a[i]>b[j] ,则把b[j]加入Rsult,j++
            if (a[aIndex] > b[bIndex]) {
                result[index] = b[bIndex];
                bIndex++;
            } else {
                result[index] = a[aIndex];
                aIndex++;
            }
            index++;
        }
        //把长的加入result
        if (aIndex == a.length) {
            for (; bIndex < b.length; bIndex++) {
                result[index ++] = b[bIndex];
            }
        }

        if (bIndex == b.length) {
            for (; aIndex < a.length; aIndex++) {
                result[index++] = a[aIndex];
            }
        }
    }

    static void mergeSort(int[] nums) {
        if (nums.length==2 || nums.length==3) {
            SelectionSort.sort(nums);
            return;
        }
        int i= nums.length >>1;

        int[] left = new int[i];
        System.arraycopy(nums, 0, left, 0, i);
        mergeSort(left);
        int[] right = new int[nums.length - i];
        System.arraycopy(nums, i , right, 0, nums.length - i);
        mergeSort(right);
        merge(nums, left, right);

    }





    public static void main(String[] args) {
        //int[] b = {1,2,6,7};
        //int[] a = {3,4,5};
        //int[] result = new int[a.length+b.length];
        //merge(result ,a, b);
        //for (int i : result) {
        //    System.out.print(i);
        //}
        int[] b = {1,2,6,5,7,3};
        mergeSort(b);
        for (int i : b) {
            System.out.print(i);
        }
    }
}
